package org.springblade.codec;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import org.springblade.cache.DeviceManagerCache;
import org.springblade.common.constant.MatchingConstant;
import org.springblade.common.tool.DateTime;
import org.springblade.handle.CodecAdapter;
import org.springblade.vo.ProtocolAnalysisVO;

import java.util.Date;
import java.util.Map;

/**
 * hello
 * @author lijiamin
 */
public class HttpCodec implements CodecAdapter {
	@Override
	public void encode(String ip, String port, String value, Long protocolAnalysisId) {
		ProtocolAnalysisVO protocolAnalysisVO = DeviceManagerCache.getDeviceManagerClient().getProtocolAnalysisOne(protocolAnalysisId);
		Integer matchingMode = protocolAnalysisVO.getMatchingMode();
		String msg = "";
		if (matchingMode == MatchingConstant.GET_MATCHING) {
			msg = sendGet(protocolAnalysisVO.getUrl(), value);
		} else if (matchingMode == MatchingConstant.POST_MATCHING) {
			msg = sendPost(protocolAnalysisVO.getUrl(), value);
		} else {
			return;
		}
		protocolAnalysisVO.setPropertyValue(msg);
		protocolAnalysisVO.setUpdateTime(DateTime.simpleDateFormat.format(new Date()));
		DeviceManagerCache.getDeviceManagerClient().updateProtocolData(protocolAnalysisVO);
	}

	private String sendGet(String url, String value) {
		Map<String, Object> map = JSONObject.parseObject(value, Map.class);
		StringBuilder strBuilder = new StringBuilder("?");
		map.forEach((k, v) -> {
			strBuilder.append(k + "=" + v + "&");
		});
		strBuilder.delete(strBuilder.length() - 1, strBuilder.length());

		String resStr = HttpRequest.get(url + strBuilder).
			timeout(20000).
			execute().
			body();
		return resStr;
	}

	private String sendPost(String url, String value) {
		String resStr = HttpRequest.post(url)
			.header(Header.CONTENT_TYPE, "application/json")
			.body(value)
			.timeout(20000)
			.execute().body();
		return resStr;
	}

	@Override
	public void decode(String ip, String port, ByteBuf byteBuf) {

	}

	@Override
	public void decode(String ip, String port, String msg) {

	}
}
